﻿using AutoMapper;
using Git.Storage.Common.Result;
using Git.Storage.DTO.EntityDTO;
using Git.Storage.Model.Entity;
using Git.Storage.WebApi.Extensions.SwaggerExtend;
using Git.Storage.WebApi.Utility.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Git.Storage.WebApi.Controllers.Pda
{
    /// <summary>
    /// PDA基本信息
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
    [CustomExceptionAsyncFilter]
    public class BasicInformationController : ControllerBase
    {


        private readonly ISqlSugarClient _Client;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="client"></param>
        public BasicInformationController(ISqlSugarClient client)
        {
            _Client = client;
        }


        /// <summary>
        ///  仓位查询
        /// </summary>
        [HttpGet]
        [ValidateAsyncActionFilter]
        public IActionResult SelectLocation()
        {
            //查整个表
            //var result1  = _Client.Queryable<Location>().ToList();
            //查表中的某个字段,条件
            var result = _Client.Queryable<Location>().Select(t => new
            {
                t.ID,
                t.LocalNum
            }).Where(t => t.ID == 1).ToList();

            return new JsonResult(new ApiDataResut<object> { Data = result });
        }




        /// <summary>
        ///  任务单查询 返回所有状态等于 1 的任务单,出入移库一块返回，子涵区分 0是入库，1是出库，2是移库
        /// </summary>
        [HttpGet]
        public IActionResult GetAudite()
        {
            var list = _Client.Queryable<Audite>()
                .Where(x => x.Status == 1)
                .ToList();

            //return Ok(list);
            return new JsonResult(new ApiDataResut<object> { Data = list });
        }

        /// <summary>
        ///  任务单详情查询,子涵传参任务类型 0是入库，1是出库，2是移库,字段二单号
        ///  根据不同任务到不同表查询 InStorDetail，OutStoDetail，MoveOrderDetail
        /// </summary>
        [HttpGet]
        public IActionResult GetDetailByType(int type)
        {
            var listAll = _Client.Queryable<Audite>()
                .Where(x => x.Status == 1 && x.TaskType == type)
                .ToList();

            try
            {
                if (listAll.Count <= 0)
                {
                    return new JsonResult(new ApiResponse<string> { Code = 200, Message = "无数据", Data = null });
                }
                if (type == 0)
                {
                    List<InStorDetail> insList = new List<InStorDetail>();

                    foreach (var item in listAll)
                    {
                        List<InStorDetail> ins = _Client.Queryable<InStorDetail>()
                        .Where(x => x.OrderNum == item.OrderNum).ToList();
                        foreach (var item2 in ins)
                        {
                            insList.Add(item2);
                        }
                    }
                    return new JsonResult(new ApiResponse<List<InStorDetail>> { Code = 200, Message = "成功", Data = insList });
                }
                else if (type == 1)
                {
                    List<OutStoDetail> outList = new List<OutStoDetail> ();

                    foreach(var item in listAll)
                    {
                        List<OutStoDetail> list = _Client.Queryable<OutStoDetail>()
                      .Where(x => x.OrderNum == item.OrderNum).ToList();
                        foreach (var item2 in list)
                        {
                            outList.Add(item2);

                        }
                    }
                  
                    return new JsonResult(new ApiResponse<List<OutStoDetail>> { Code = 200, Message = "成功", Data = outList });

                }
                else if (type == 2)
                {
                    List<MoveOrderDetail> moveList = new List<MoveOrderDetail>();
                    foreach (var item in listAll)
                    {
                        List<MoveOrderDetail> list = _Client.Queryable<MoveOrderDetail>()
                        .Where(x => x.OrderNum == item.OrderNum).ToList();
                        foreach(var item2 in list)
                        {
                            moveList.Add(item2);

                        }
                    }
 

                    return new JsonResult(new ApiResponse<List<MoveOrderDetail>> { Code = 200, Message = "成功", Data = moveList });

                }
                else
                {
                    return new JsonResult(new ApiResponse<string> { Code = 200, Message = "", Data = null });
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }
        }



        /// <summary>
        /// 下发任务 子涵传参，托盘条码，任务单号，任务类型（0入库，1出库，2移库），agv起点，agv终点（agv终点是堆垛机起点），堆垛机的终点
        /// 192.168.50.131:81/api/WCS/TaskComplete
        /// </summary>
        ///taskType 任务类型 IN OUT MOVE等 DeliverSn 任务单号,
        [HttpPost]
        public async Task<IActionResult> DeliverTheTask(string PalletCode, string taskId, string tackType, string ZaiHuTai, string KuKou, string KuWei)
        {
            try
            {
                // 定义变量并赋值
                string reqCode = Guid.NewGuid().ToString();
                string taskTyp = "F01";
                //起点
                string positionCode1 = ZaiHuTai;
                string type1 = "00";
                //终点
                string positionCode2 = KuKou;
                string type2 = "00";
                string kk = "";
                if(KuKou == "K01")
                {
                    kk = "15-1-1";
                }
                else if(KuKou == "K02")
                {
                    kk = "11-1-1";
                }
                else if (KuKou == "K03")
                {
                    kk = "7-1-1";
                }
                else if (KuKou == "K04")
                {
                    kk = "3-1-1";
                }
                using (HttpClient httpClient = new HttpClient())
                {

                    object obj = new
                    {
                        taskId = taskId,
                        tackType = tackType,
                        taskLevel = 0,
                        taskSubType = tackType,
                        startPositionId = kk,
                        endPositionId = KuWei,
                        trayHeight = 0,
                        PalletCode = PalletCode
                    };
                    if(tackType == "OUT")
                    {
                        positionCode2 = ZaiHuTai;
                        positionCode1 = KuKou;
                        obj = new
                        {
                            taskId = taskId,
                            tackType = tackType,
                            taskLevel = 0,
                            taskSubType = tackType,
                            startPositionId = KuWei,
                            endPositionId = kk,
                            trayHeight = 0,
                            PalletCode = PalletCode
                        };
                    }

                   

                    // 构建JSON字符串
                    string agvjson = $@"{{
    ""reqCode"": ""{reqCode}"",
    ""reqTime"": """",
    ""clientCode"": """",
    ""tokenCode"": """",
    ""taskTyp"": ""{taskTyp}"",
    ""sceneTyp"": """",
    ""ctnrTyp"": """",
    ""ctnrCode"": """",
    ""wbCode"": """",
    ""positionCodePath"": [
        {{
            ""positionCode"": ""{positionCode1}"",
            ""type"": ""{type1}""
        }},
        {{
            ""positionCode"": ""{positionCode2}"",
            ""type"": ""{type2}""
        }}
    ],
    ""podCode"": """",
    ""podDir"": """",
    ""podTyp"": """",
    ""materialLot"": """",
    ""priority"": """",
    ""agvCode"": """",
    ""taskCode"": """",
    ""data"": """"
}}";

                    if(tackType == "IN")
                    {
                        //agv接口
                        var agvcontent = new StringContent(agvjson, Encoding.UTF8, "application/json");
                        string agvurl = "http://192.168.50.138:8182/rcms/services/rest/hikRpcService/genAgvSchedulingTask";
                        var agvresponse = await httpClient.PostAsync(agvurl, agvcontent);
                    }
                    else
                    {
                        var parameters = new List<SugarParameter>()
                    {
                        new SugarParameter("@OrderNum", taskId), // 存储过程参数1
                        new SugarParameter("@AgvJson", agvjson)
            };

                        parameters.ForEach(p => p.Direction = System.Data.ParameterDirection.Input);

                        _Client.Ado.UseStoredProcedure()
                           .GetDataTable("Proc_Audite", parameters.ToArray());
                    }
                    
                    string json = JsonConvert.SerializeObject(obj);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    string url = "http://192.168.50.131:8083/api/ReceiveTask";
                    var response = await httpClient.PostAsync(url, content);

                    if (response.IsSuccessStatusCode)
                    {
                        return Ok("任务交付成功");
                    }
                    else
                    {
                        return BadRequest("任务交付失败");
                    }
                }
            }
            catch (Exception ex)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, "Internal server error");
            }
        }




        ///// <summary>
        ///// 任务上报例子
        ///// </summary>
        //[HttpPost]
        //[ValidateAsyncActionFilter]
        //public IActionResult TaskFeedback(TaskFeedbackDTO taskFeedbackDTO)
        //{
        //    string orderNum = taskFeedbackDTO.TypeCode;
        //    //调用存储过程
        //    var parameters = new List<SugarParameter>()
        //    {
        //        new SugarParameter("@OrderNum", orderNum), // 存储过程参数1
        //        new SugarParameter("@Status", 2), // 存储过程参数2
        //        new SugarParameter("@AuditUser", "默认"), // 存储过程参数2
        //        new SugarParameter("@Reason", ""), // 存储过程参数2
        //        new SugarParameter("@OperateType", 1), // 存储过程参数2
        //        new SugarParameter("@EquipmentNum", ""), // 存储过程参数2
        //        new SugarParameter("@EquipmentCode", ""), // 存储过程参数2
        //        new SugarParameter("@Remark", "")
        //        // 添加其他参数...
        //    };

        //    parameters.ForEach(p => p.Direction = System.Data.ParameterDirection.Input);

        //    var outputParameter = new SugarParameter("@ReturnValue", null, (System.Data.DbType)System.Data.ParameterDirection.Output);
        //    parameters.Add(outputParameter);

        //    var dt = _Client.Ado.UseStoredProcedure()
        //                    .GetDataTable("Proc_AuditeInStorage", parameters.ToArray());

        //    var outputValue =dt; // 获取输出参数的值


        //    return new JsonResult(new ApiDataResut<object> { Data = outputValue });
        //}

        /// <summary>
        /// 吉林wcs任务上报
        /// </summary>
        [HttpPost]
        [ValidateAsyncActionFilter]
        public IActionResult wcsTaskComplete(TaskFeedbackDTO taskFeedbackDTO)
        {
            string message = "任务反馈成功";
            int code = 0;
            string ordernum = taskFeedbackDTO.taskId;
            bool success = true;
            //根据任务首字母判断是入库，出库，移库

            string taskType = taskFeedbackDTO.taskId.Substring(0, 1);

            //验证单号有没有


            // 处理异常情况
            var response = new
            {
                success = success,
                code = code,
                message = message
            };
            try
            {
                // 根据业务逻辑进行任务反馈的处理
                if (string.IsNullOrEmpty(ordernum))
                {
                    success = false;
                    code = 500;
                    message = "任务单号不能为null";
                }
                if (taskFeedbackDTO.finishType != 0)
                {
                    // 处理异常情况
                    return null;
                }
                //入库
                if (taskType == "R")
                {
                    //调用存储过程
                    var parameters = new List<SugarParameter>()
                    {
                        new SugarParameter("@OrderNum", ordernum), // 存储过程参数1
                        new SugarParameter("@Status", 2), // 存储过程参数2
                        new SugarParameter("@AuditUser", "默认"), // 存储过程参数2
                        new SugarParameter("@Reason", ""), // 存储过程参数2
                        new SugarParameter("@OperateType", 2), // 存储过程参数2
                        new SugarParameter("@EquipmentNum", ""), // 存储过程参数2
                        new SugarParameter("@EquipmentCode", ""), // 存储过程参数2
                        new SugarParameter("@Remark", "")

            };

                    parameters.ForEach(p => p.Direction = System.Data.ParameterDirection.Input);

                    var outputParameter = new SugarParameter("@ReturnValue", null, (System.Data.DbType)System.Data.ParameterDirection.Output);
                    parameters.Add(outputParameter);
                    _Client.Ado.UseStoredProcedure()
                       .GetDataTable("Proc_AuditeInStorage", parameters.ToArray());

                }
                //出库
                else if (taskType == "C")
                {
                    //调用存储过程
                    var parameters = new List<SugarParameter>()
                    {
                        new SugarParameter("@OrderNum", ordernum), // 存储过程参数1
                        new SugarParameter("@Status", 2), // 存储过程参数2
                        new SugarParameter("@AuditUser", "默认"), // 存储过程参数2
                        new SugarParameter("@Reason", ""), // 存储过程参数2
                        new SugarParameter("@OperateType", 2), // 存储过程参数2
                        new SugarParameter("@EquipmentNum", ""), // 存储过程参数2
                        new SugarParameter("@EquipmentCode", ""), // 存储过程参数2
                        new SugarParameter("@Remark", "")
            };

                    parameters.ForEach(p => p.Direction = System.Data.ParameterDirection.Input);


                    var outputParameter = new SugarParameter("@ReturnValue", null, (System.Data.DbType)System.Data.ParameterDirection.Output);
                    parameters.Add(outputParameter);
                    _Client.Ado.UseStoredProcedure()
                       .GetDataTable("Proc_AuditeOutStorage", parameters.ToArray());

                    //堆垛机任务完成在调用agv小车过来取货


                    List<Audite> listresult = _Client.Queryable<Audite>()
                      .Where(x => x.OrderNum == ordernum).ToList();
                    string agvjson = "";
                    foreach (var item in listresult)
                    {
                        agvjson = item.AgvJson;
                    }
                    HttpClient httpClient = new HttpClient();
                    
                    var agvcontent = new StringContent(agvjson, Encoding.UTF8, "application/json");
                    string agvurl = "http://192.168.50.138:8182/rcms/services/rest/hikRpcService/genAgvSchedulingTask";
                    var agvresponse = httpClient.PostAsync(agvurl, agvcontent);
                    var parametersagv = new List<SugarParameter>()
                    {
                        new SugarParameter("@OrderNum", ordernum), // 存储过程参数1
                        new SugarParameter("@AgvJson", "agv已完成")
            };

                    parametersagv.ForEach(p => p.Direction = System.Data.ParameterDirection.Input);

                    _Client.Ado.UseStoredProcedure()
                       .GetDataTable("Proc_Audite", parametersagv.ToArray());
                }
                //移库
                else if (taskType == "Y")
                {
                    //调用存储过程
                    var parameters = new List<SugarParameter>()
                    {
                        new SugarParameter("@OrderNum", ordernum), // 存储过程参数1
                        new SugarParameter("@Status", 2), // 存储过程参数2
                        new SugarParameter("@AuditUser", "默认"), // 存储过程参数2
                        new SugarParameter("@Reason", ""), // 存储过程参数2
                        new SugarParameter("@OperateType", 2), // 存储过程参数2
                        new SugarParameter("@EquipmentNum", ""), // 存储过程参数2
                        new SugarParameter("@EquipmentCode", ""), // 存储过程参数2
                        new SugarParameter("@Remark", "")
            };

                    parameters.ForEach(p => p.Direction = System.Data.ParameterDirection.Input);

                    var outputParameter = new SugarParameter("@ReturnValue", null, (System.Data.DbType)System.Data.ParameterDirection.Output);
                    parameters.Add(outputParameter);
                    _Client.Ado.UseStoredProcedure()
                       .GetDataTable("Proc_AuditeMove", parameters.ToArray());
                }
                else
                {
                    success = false;
                    code = 500;
                    message = "任务类型不对";
                }
                // 假设在此处对任务进行处理，并得到处理结果
                response = new
                {
                    success = success,
                    code = code,
                    message = message
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                response = new
                {
                    success = success,
                    code = code,
                    message = message
                };
                return Ok(response);
            }
        }
    }
}


public class ApiResponse<T>
{
    public int Code { get; set; }
    public string Message { get; set; }
    public T Data { get; set; }
}